<template>
  <div>
<!--    面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

<!--    卡片视图-->
    <el-card class="box-card">
<!--      头部警告-->
      <el-alert
          title="注意：只允许为第三级分类设置相关参数！"
          type="warning"
          :closable="false"
          show-icon>
      </el-alert>
<!--      选择商品分类按钮-->
      <el-row class="cat_opt">
        <el-col>
          <span>
            选择商品分类：
            <!--              options用于指定数据源-->
            <!--          props用于指定配置对象-->
          <el-cascader
              v-model="selectedKeys"
              :options="categoryList"
              :props="{ expandTrigger: 'hover' ,...cascaderProps}"
              clearable
              @change="handleChange">
          </el-cascader>
          </span>
        </el-col>
      </el-row>
<!--      tab页签区域-->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
<!--        添加动态参数面板-->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary"
                     size="mini"
                     :disabled="isBtnDisable"
                     @click="addDialogVisible = true"
                     >
            添加参数
          </el-button>
<!--          动态表格-->
          <el-table :data="manyTableData" border stripe>
<!--            展开页-->
            <el-table-column type="expand">
              <template slot-scope="scope">
               <div class="params-tag">
                 <el-tag
                     class="params-tag-item"
                     v-for="(item,index) in scope.row.attr_vals"
                     :key="index"
                     closable @close="handleTagClose(index,scope.row)">
                   {{item}}
                 </el-tag>
<!--                 输入文本框-->
                 <el-input
                     class="input-new-tag"
                     v-if="scope.row.inputVisible"
                     v-model="scope.row.inputValue"
                     ref="saveTagInput"
                     size="small"
                     @keyup.enter.native="handleInputConfirm(scope.row)"
                     @blur="handleInputConfirm(scope.row)">
                 </el-input>
<!--                 添加按钮-->
                 <el-button
                     v-else size="small"
                     @click="showInput(scope.row)">+ New Tag</el-button>
               </div>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                    type="primary"
                    icon="el-icon-edit"
                    size="mini"
                    @click="showEditDialog(scope.row.attr_id)">
                  编辑
                </el-button>
                <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    @click="removeParams(scope.row.attr_id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
<!--        添加静态属性面板-->
        <el-tab-pane label="静态属性" name="only">
          <el-button
              type="primary"
              size="mini"
              :disabled="isBtnDisable"
              @click="addDialogVisible = true">
            添加属性
          </el-button>
<!--          静态属性表格-->
          <el-table :data="onlyTableData" border stripe>
<!--            展开行-->
            <el-table-column type="expand">
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <div class="params-tag">
                    <el-tag
                        class="params-tag-item"
                        v-for="(item,index) in scope.row.attr_vals"
                        :key="index"
                        closable @close="handleTagClose(index,scope.row)">
                      {{item}}
                    </el-tag>
                    <!--                 输入文本框-->
                    <el-input
                        class="input-new-tag"
                        v-if="scope.row.inputVisible"
                        v-model="scope.row.inputValue"
                        ref="saveTagInput"
                        size="small"
                        @keyup.enter.native="handleInputConfirm(scope.row)"
                        @blur="handleInputConfirm(scope.row)">
                    </el-input>
                    <!--                 添加按钮-->
                    <el-button
                        v-else size="small"
                        @click="showInput(scope.row)">+ New Tag</el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                    type="primary"
                    icon="el-icon-edit"
                    size="mini"
                    @click="showEditDialog(scope.row.attr_id)">
                  编辑
                </el-button>
                <el-button type="danger"
                           icon="el-icon-delete"
                           size="mini"
                           @click="removeParams(scope.row.attr_id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
<!--    添加参数对话框-->
    <el-dialog
        :title="'添加' + titleText"
        :visible.sync="addDialogVisible"
        width="50%" @close="addDialogClosed">
<!--      添加参数表单-->
      <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRefs" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
       <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

<!--    编辑参数对话框-->
    <el-dialog
        :title="'编辑' + titleText"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClosed">
      <!--      编辑参数表单-->
      <el-form
          :model="editForm"
          :rules="editFormRoles"
          ref="editFormRefs"
          label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>


</template>

<script>
export default {
  name: "Params",
  data(){
    return{
      // 分类列表
      categoryList: [],
      // 选中的分类，双向绑定到的数组
      selectedKeys:[],
      // 级联选择器的配置对象
      cascaderProps:{
        // 选中的值
        value:"cat_id",
        // 展示的值
        label:"cat_name",
        // 父子级嵌套属性
        children:"children"
      },
      // 被激活页签的名称,默认激活的页签
      activeName:"many",
      //动态表格数据
      manyTableData:[],
      // 静态表格数据
      onlyTableData:[],
      //控制添加对话框的显示与隐藏
      addDialogVisible:false,
      // 添加参数的表单
      addForm:{
        attr_name:""
      },
      addFormRules:{
        attr_name: [
          {required:true,message:"请输入参数名称",trigger:"blur"}
        ]
      },
      // 控制编辑参数对话框的显示与隐藏
      editDialogVisible:false,
      // 编辑参数的表单
      editForm:{
        attr_name:""
      },
      // 编辑表单的验证规则
      editFormRoles:{
        attr_name: [
          {required:true,message:"请输入参数名称",trigger:"blur"}
        ]
      },
    }

  },
  created() {
    this.getCategoryList()
  },
  methods:{
    //获取分类列表
   async getCategoryList(){
    const {data:res} = await this.$http.get("categories")
     if(res.meta.status !== 200){
       return this.$message.error("获取商品分类失败")
     }
     this.categoryList = res.data
    },

    //处理级联选择框的变化
   handleChange(){
     this.getParamsData()
    },
    // 处理Tabs页签点击事件
    handleTabClick(){
     this.getParamsData()
    },
    // 获取参数的列表数据
    async getParamsData(){
      if(this.selectedKeys.length < 3){
        this.selectedKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      const {data:res} = await this.$http.get(
          `categories/${this.cateID}/attributes`,{
            params:{sel:this.activeName}
          })
      if(res.meta.status !== 200){
        return this.$message.error("获取参数列表失败！")
      }
      res.data.forEach((item)=>{
        item.attr_vals = item.attr_vals? item.attr_vals.split(",") : []
        //单独控制每一行的文本框的显示与隐藏
        item.inputVisible = false
        item.inputValue = ""
      })
      if(this.activeName === "many"){
        this.manyTableData = res.data
      }else{
        this.onlyTableData = res.data
      }
    },
    //监听添加参数对话框的关闭事件
    addDialogClosed(){
     this.$refs.addFormRefs.resetFields()
    },
    // 点击添加参数
    addParams(){
     this.$refs.addFormRefs.validate(async valid=>{
       if(!valid) return
     const {data:res} = await this.$http.post(`categories/${this.cateID}/attributes`,{
         attr_name:this.addForm.attr_name,
         attr_sel:this.activeName
       })
       if(res.meta.status !== 201){
         return this.$message.error("添加参数失败")
       }
       this.$message.success("添加参数成功")
       this.getParamsData()
       this.addDialogVisible = false
     })
    },
    //显示编辑参数对话框
   async showEditDialog(id){
     // 查询当前参数信息
    const {data:res} = await this.$http.get(`categories/${this.cateID}/attributes/${id}`,{
       params:{attr_sel:this.activeName}
     })
     if(res.meta.status!== 200) return this.$message.error("获取参数信息失败")
     this.editForm = res.data
     this.editDialogVisible = true
    },
    // 监听编辑参数对话框的关闭事件
    editDialogClosed(){
     this.$refs.editFormRefs.resetFields()
    },
    //修改参数
    editParams(){
     this.$refs.editFormRefs.validate(async valid=>{
       if(!valid) return
       const {data:res} = await this.$http.put(`categories/${this.cateID}/attributes/${this.editForm.attr_id}`,
           {
           attr_name:this.editForm.attr_name,
           attr_sel:this.activeName
           })
       if(res.meta.status !== 200) return this.$message.error("修改参数失败")
       this.$message.success("修改参数成功")
       this.getParamsData()
       this.editDialogVisible = false
     })
    },
    // 删除参数
    async removeParams(id){
     const confirmResult = await this.$confirm("此操作将会永久删除此参数，是否继续？","提示",{
       confirmButtonText:"确定",
       cancelButtonText:"取消",
       type:"warning"
     }).catch(err=>err)
      if(confirmResult !== "cancel"){
        const {data:res} = await this.$http.delete(`categories/${this.cateID}/attributes/${id}`)
        if(res.meta.status !== 200) return this.$message.error("删除失败")
        this.$message.success("删除成功")
        this.getParamsData()
      }else{
        this.$message.info("已取消删除")
      }
    },
    // 点击显示文本框
    showInput(param){
     param.inputVisible = true
      this.$nextTick(()=>{
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    //处理文本框按下回车和失去焦点的事件
   async handleInputConfirm(param){
      if(param.inputValue.trim().length === 0){
        param.inputValue = ""
        param.inputVisible = false
        return
      }
      //如果没有return则进行添加操作
      param.attr_vals.push(param.inputValue.trim())
     param.inputValue = ""
     param.inputVisible = false
     const {data:res} = await this.$http.put(`categories/${this.cateID}/attributes/${param.attr_id}`,{
       attr_name:param.attr_name,
       attr_sel:param.attr_sel,
       attr_vals:param.attr_vals.join(",")
     })
     if(res.meta.status!==200) return this.$message.error("修改参数项失败")
     this.$message.success("修改参数项成功")
    },

    // 删除标签参数项
    async handleTagClose(index,param){
     param.attr_vals.splice(index,1)
      const {data:res} = await this.$http.put(`categories/${this.cateID}/attributes/${param.attr_id}`,{
        attr_name:param.attr_name,
        attr_sel:param.attr_sel,
        attr_vals:param.attr_vals.join(",")
      })
      if(res.meta.status!==200) return this.$message.error("修改参数项失败")
      this.$message.success("修改参数项成功")
    }

  },
  computed:{
    // 禁用为true，可用为false
    isBtnDisable(){
      return this.selectedKeys.length !== 3
    },
    // 选择三级分类的id
    cateID(){
      if(this.selectedKeys.length === 3){
        return this.selectedKeys[this.selectedKeys.length-1]
      }
      return null
    },
    //动态计算标题文本
    titleText(){
      if(this.activeName === "many"){
        return "动态参数"
      }else{
        return  "静态属性"
      }
    }
  }
}
</script>

<style scoped>
.cat_opt{
  margin-top: 15px;
}
.params-tag{
  margin-left: 50px;
}
.params-tag-item{
  margin-right: 10px;
  margin-bottom: 10px;
}
.input-new-tag{
  width: 150px;
}
</style>